package com.swdegao.iot.netty.listener;


import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import com.swdegao.iot.SwdegaoIotMgtServerApplication;
import com.swdegao.iot.netty.entity.MyProps;
import com.swdegao.iot.netty.thread.NettyServerThread;
import com.swdegao.iot.netty.thread.NettyUdpServerThread;


@WebListener
public class NettySocketListener implements ServletContextListener{

	// 定义一个全局的记录器，通过LoggerFactory获取
	private final static Logger logger = LoggerFactory.getLogger(NettySocketListener.class);
    private NettyServerThread nettyServerThread;
    private NettyUdpServerThread nettyUdpServerThread;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ApplicationContext context = (ApplicationContext)servletContextEvent.getServletContext()
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        MyProps myProps = (MyProps)context.getBean("myProps");
//        int port = myProps.getMyport();
//        int udpport = myProps.getMyudpport();
        int tcpisopen = myProps.getTcpisopen();
        int udpisopen = myProps.getUdpisopen();
        if(1 == tcpisopen){
            logger.info("开始执行tcp启动服务");
            nettyServerThread = new NettyServerThread(myProps.getPorts());
            nettyServerThread.start();
        }
        if(1 == udpisopen){
            logger.info("开始执行Udp启动服务");
       	 	nettyUdpServerThread = new NettyUdpServerThread(myProps.getPorts());
       	 	nettyUdpServerThread.start();
       }
    }

    /**
     * tomcat关闭时，关闭线程，释放端口
     * @param servletContextEvent
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        nettyServerThread.stopThread(true);
        logger.info("Project NettyServerThread End");
    }

}
